package com.unohacha.qqj.fzdr.fragment;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.adapter.BaseRVAdapter;
import com.unohacha.qqj.fzdr.adapter.BaseViewHolder;
import com.unohacha.qqj.fzdr.bean.homebean.HomeAppLogisBean;
import com.unohacha.qqj.fzdr.bean.homebean.HomeBannerBean;
import com.unohacha.qqj.fzdr.imp.MyApplication;
import com.unohacha.qqj.fzdr.imp.MyCallBack;
import com.unohacha.qqj.fzdr.imp.UrlConfig;
import com.unohacha.qqj.fzdr.imp.XUtil;
import com.unohacha.qqj.fzdr.main.TransportActivity;
import com.unohacha.qqj.fzdr.main.sends.SendWlActivity;
import com.unohacha.qqj.fzdr.personal.view.activity.WuliuDetailActivity;
import com.unohacha.qqj.fzdr.util.GlideImageLoader;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.mylibrary.base.BaseActivity;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 物流信息 item_material_info
 */
public class MaterialInfoActivity extends BaseActivity implements OnRefreshLoadmoreListener {


    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    @BindView(R.id.common_right_text)
    TextView commonRightText;
    @BindView(R.id.edt_seach)
    EditText edtSeach;
    @BindView(R.id.common_right_search)
    TextView commonRightSearch;
    @BindView(R.id.search_ll)
    LinearLayout searchLl;
    @BindView(R.id.comment_banner)
    Banner banner;
    @BindView(R.id.car_list_recycler)
    RecyclerView carListRecycler;
    @BindView(R.id.mRefreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.qiu_hy_tv)
    TextView qiu_hy_tv;
    
    private int page = 1;
    private List<HomeBannerBean.DataBean> mBannerAllList = new ArrayList<>();//banner的集合
    private List<String> mBannerList = new ArrayList<>();
    private List<HomeAppLogisBean.DataBeanX.DataBean> mAppLogiList = new ArrayList<>();
    private BaseRVAdapter mBaseAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_material_info;
    }

    @Override
    protected void initView() {
        super.initView();
        commonTitle.setText(getResources().getString(R.string.logistics_info));
        commonRightImage.setVisibility(View.GONE);
        commonRightText.setText(getResources().getString(R.string.road_send));
        initRefreshLayout();
        getBannerData(31);
        getAppMaterialList(Prefer.obtainReLocation(this),"");
        
    }

    private void initRefreshLayout() {
        mRefreshLayout.setOnRefreshLoadmoreListener(this);
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(this));
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(this));
        carListRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
    }

    @OnClick({R.id.common_back, R.id.common_right_text,
            R.id.common_right_search,R.id.qiu_hy_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                finish();
                break;
            case R.id.common_right_search://搜索
                if (!TextUtils.isEmpty(edtSeach.getText().toString().trim())){
                    page = 1;
                    getAppMaterialList(Prefer.obtainReLocation(this),edtSeach.getText().toString().trim());
                }else {
                    MyToast("请输入搜索内容!");
                    return;
                }
                break;
            case R.id.common_right_text://路线发布
                Intent intent = new Intent(MaterialInfoActivity.this, SendWlActivity.class);
                startActivity(intent);
                break;
            case R.id.qiu_hy_tv://求货运
                Intent intent1 = new Intent(MaterialInfoActivity.this,TransportActivity.class);
                startActivity(intent1);
                break;
        }
    }

    //物流分类列表
    private void getAppMaterialList(String address_id,String keyword){

        String la = Prefer.getInstance().obtainLocation(this).substring(0, Prefer.getInstance().obtainLocation(this).indexOf(","));
        String lon = Prefer.getInstance().obtainLocation(this).substring(
                Prefer.getInstance().obtainLocation(this).indexOf(",") + 1,
                Prefer.getInstance().obtainLocation(this).length());
        
        Map<String,Object> params = new HashMap<>();
        params.put("address_id",address_id);
        params.put("keyword",keyword);
        params.put("long",lon);
        params.put("lat",la);
        params.put("page",page);
        XUtil.Post(UrlConfig.APP_LOGISTICS_LIST,params,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (1 == jsonObject.optInt("code")){
                        Gson gson = new Gson();
                        HomeAppLogisBean logisBean = gson.fromJson(result,HomeAppLogisBean.class);
                        if (null != logisBean){
                            if (page == 1){
                                
                                if (null != mAppLogiList){
                                    mAppLogiList.clear();
                                }
                                mAppLogiList.addAll(logisBean.getData().getData());
                                mRefreshLayout.finishRefresh();
                                mRefreshLayout.resetNoMoreData();
                            }else {
                                mRefreshLayout.finishLoadmore();
                                mBaseAdapter.notifyDataSetChanged();
                            }

                            setAppLogiAdapter();
                        }
                    }else if (100 == jsonObject.optInt("code")){
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                        if (page == 1){
                            MyToast(jsonObject.optString("message"));
                            mRefreshLayout.finishRefresh();
                            mRefreshLayout.resetNoMoreData();
                            if (null != mAppLogiList){
                                mAppLogiList.clear();
                            }
                            mBaseAdapter.notifyDataSetChanged();
                        }else {
                            MyToast(getResources().getString(R.string.no_more_data));
                            mRefreshLayout.finishLoadmore();
                            mRefreshLayout.finishLoadmoreWithNoMoreData();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }
    
    //设置数据
    private void setAppLogiAdapter(){
        mBaseAdapter = new BaseRVAdapter(this,mAppLogiList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_material_info;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                ImageView iv_wul = holder.getImageView(R.id.iv_wul);
                TextView express_name = holder.getTextView(R.id.express_name);
                TextView contact_name = holder.getTextView(R.id.contact_name);
                TextView contact_phone = holder.getTextView(R.id.contact_phone);
                TextView tv_address = holder.getTextView(R.id.tv_address);
                TextView deliver_road = holder.getTextView(R.id.deliver_road);
                if (null != mAppLogiList){
                    if (!TextUtils.isEmpty(mAppLogiList.get(position)
                            .getAttachment_id())) {
                        Glide.with(MaterialInfoActivity.this).load(mAppLogiList.get(position)
                        .getAttachment_id()).into(iv_wul);
                    }else {
                        iv_wul.setBackgroundColor(getResources().getColor(R.color.bg_gray));
                    }
                    express_name.setText(mAppLogiList.get(position).getName());
                    contact_name.setText("联系人：" + mAppLogiList.get(position).getContact());
                    contact_phone.setText("电话：" + mAppLogiList.get(position).getTelephone());
                    tv_address.setText("电话：" + mAppLogiList.get(position).getCompany_add());
                    deliver_road.setText("路线：" + mAppLogiList.get(position).getRoute_start()  + 
                            mAppLogiList.get(position).getRoute_channel() + mAppLogiList.get(position).getRoute_end());
                }
            }
        };
        
        carListRecycler.setAdapter(mBaseAdapter);
        mBaseAdapter.addItemClickListener(new BaseRVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                Intent intent = new Intent(MaterialInfoActivity.this, WuliuDetailActivity.class);
//                intent.putExtra("address_id", address_id + "");
                intent.putExtra("id", mAppLogiList.get(position).getId() + "");
//                intent.putExtra("name", mAppDataList.get(position).getName() + "");
//                intent.putExtra("type", mFragmentsTitle.get(mTabLayout.getSelectedTabPosition()) + "");
                startActivity(intent);
            }
        });
    }
    
    //获取banner 集合数据
    private void getBannerData(int typeid) {
        Map<String, Object> params = new HashMap<>();
        params.put("token", Prefer.getInstance().getToken());
        params.put("typeid", typeid);//4-面料供求 5-制造供求 6-原料供求 7-辅料供应 8-人才招聘 29-求职发布
        XUtil.Post(UrlConfig.AD_LIST, params, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    mRefreshLayout.finishRefresh();
                    mRefreshLayout.resetNoMoreData();
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.optString("code"))) {
                        Gson gson = new Gson();
                        HomeBannerBean bannerBean = gson.fromJson(result, HomeBannerBean.class);
                        if (null != bannerBean) {
                            if (null != mBannerAllList) {
                                mBannerAllList.clear();
                            }
                            mBannerAllList.addAll(bannerBean.getData());
                            setBannerData();
                        }
                        mRefreshLayout.finishLoadmore();
                        mRefreshLayout.finishLoadmoreWithNoMoreData();
                    } else if ("100".equals(jsonObject.optString("code"))) {
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    } else {
                        MyToast(jsonObject.optString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    //设置banner 数据
    private void setBannerData() {
        if (null != mBannerAllList) {
            for (int i = 0; i < mBannerAllList.size(); i++) {
                mBannerList.add(i, mBannerAllList.get(i).getImg_face());
            }
            banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);//设置圆形指示器与标题
            banner.setIndicatorGravity(BannerConfig.CENTER);//设置指示器位置
            banner.setImages(mBannerList);
            banner.setImageLoader(new GlideImageLoader());
            banner.start();

            banner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int position) {
                    //用mBannerAllList集合
                }
            });
        }
    }
    
    
    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                page ++;
                getBannerData(31);
                getAppMaterialList(Prefer.obtainReLocation(MaterialInfoActivity.this),"");
            }
        },2000);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                page = 1;
                getBannerData(31);
                getAppMaterialList(Prefer.obtainReLocation(MaterialInfoActivity.this),"");
            }
        },2000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
